<?php

namespace App\Module\Api\Controllers;

use App\Module\Api\Controllers\Request\SessionRequest;
use App\Module\Api\Validator\SessionValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;


class SessionController extends Controller
{
    public function __construct()
    {
        $this->query = new SessionRequest();
        parent::__construct();
    }

    /**
     * 初次请求获取SessionId 接口方法
     * @param Request $request
     * @throws \App\Exceptions\Customize\ParamsException
     */
    public function index()
    {
        (new SessionValidator())->check();

        $action = $this->query->action;
        $deviceType = $this->query->deviceType;
        //用户请求且为微信客户端才返回sessionId
        if ($action==1 && $deviceType==4){
            $sessionId = $this->createSessionId();
            $userInfo=[];
            Cache::put($sessionId,$userInfo,config('app.cache_time'));
            // 计算过期时间
            $expire=date('Y-m-d H:i:s',time()+config('app.cache_time'));
            //拼接数据
            \request()->s = $sessionId;
            $data = ['expire'=>$expire];
            return apiResponse($data);
        }

    }

    /**
     * 创建sessionId 防止sessionId重复
     * @return string
     */
    public function createSessionId(){
        $sessionId=str_random(30);
        $flag = Cache::offsetExists($sessionId);
        if ($flag){
           return  $this->createSessionId();
        }else{
            return $sessionId;
        }
    }
}
